import { EventEmitter } from 'events'

export default class Tools {
  static ua = window.navigator.userAgent.toLowerCase()

  static isEmptyObj(data) {
    if (JSON.stringify(data) === '{}') {
      return false // 如果为空,返回false
    }
    return true // 如果不为空，则会执行到这一步，返回true
  }

  static getUrlParams = (name) => {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i')
    const r = window.location.href.slice(window.location.href.indexOf('?') + 1).match(reg)
    if (r != null) {
      return decodeURI(r[2])
    }
    return null
  }

  static format = (str) => {
    const oDate = new Date(str)
    const oYear = oDate.getFullYear()
    const oMonth = oDate.getMonth() + 1
    const oDay = oDate.getDate()
    // const oHour = oDate.getHours()
    // const oMin = oDate.getMinutes()
    // const oSen = oDate.getSeconds()
    const oTime = `${oYear}-${this.addZero(oMonth)}-${this.addZero(oDay)}`
    // ${addZero(oHour)}:${addZero(oMin)}:${addZero(oSen)}
    return oTime
  }

  static addZero = (num) => {
    if (parseInt(num, 10) < 10) {
      num = `0${num}`
    }
    return num
  }

  static intactFormatTime = (str) => {
    const oDate = new Date(str)
    const oYear = oDate.getFullYear()
    const oMonth = oDate.getMonth() + 1
    const oDay = oDate.getDate()
    const oHour = oDate.getHours()
    const oMin = oDate.getMinutes()
    const oSen = oDate.getSeconds()
    const oTime = `${oYear}-${this.addZero(oMonth)}-${this.addZero(oDay)} ${this.addZero(oHour)}:${this.addZero(
      oMin,
    )}:${this.addZero(oSen)}`
    return oTime
  }

  static Bus = new EventEmitter()

  static downloadFile = (url) => {
    // 获得id为downLoadListFrame的frame
    let divFrame = window.parent.document.getElementById('downLoadListFrame')
    // 判断是否存在，如果存在先移除，再重新创建
    if (divFrame != null) {
      window.parent.document.body.removeChild(divFrame)
    }
    // 重新创建
    const iframe = window.parent.document.createElement('iframe')
    iframe.setAttribute('id', 'downLoadListFrame')
    window.parent.document.body.appendChild(iframe)
    divFrame = window.parent.document.getElementById('downLoadListFrame')
    // 隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
    divFrame.src = url
    divFrame.style.display = 'none'
  }
}
